(function(){
  'use strict';

  var mount = document.getElementById('admin-create-strategy');
  var card = document.getElementById('admin-create-strategy-card');
  if (!mount || !card) return;
  if (!window.AppApi) return;

  function el(tag, props, children){
    var e = document.createElement(tag);
    if (props){ for (var k in props){ if (k==='className') e.className=props[k]; else if (k==='text') e.textContent=props[k]; else e.setAttribute(k, props[k]); } }
    if (children){ for (var i=0;i<children.length;i++) e.appendChild(children[i]); }
    return e;
  }

  function renderForm(){
    mount.innerHTML = '';
    var form = el('form', { id: 'admin-create-form', className: 'form' });
    var f1 = el('div', { className: 'field' }, [ el('label',{text:'策略名称'}), el('input',{className:'input',id:'adm-name',placeholder:'如 趋势跟随'}) ]);
    var f2 = el('div', { className: 'field' }, [ el('label',{text:'交易符号（单个）'}), el('input',{className:'input',id:'adm-symbol',placeholder:'如 BTC-USDT'}) ]);
    var f3 = el('div', { className: 'field' }, [ el('label',{text:'市场类型'}), (function(){ var s=el('select',{className:'input',id:'adm-market'}); var o1=el('option',{value:'spot',text:'spot（现货）'}); var o2=el('option',{value:'perpetual',text:'perpetual（合约）'}); s.appendChild(o1); s.appendChild(o2); return s; })() ]);
    var msg = el('div', { id:'adm-msg', className:'form-msg' });
    var result = el('div', { id:'adm-result' });
    var btn = el('button', { className:'btn primary', type:'submit' }); btn.textContent='创建';
    form.appendChild(f1); form.appendChild(f2); form.appendChild(f3); form.appendChild(msg); form.appendChild(result); form.appendChild(btn);

    form.addEventListener('submit', async function(ev){
      ev.preventDefault();
      msg.textContent = '提交中...';
      var name = document.getElementById('adm-name').value.trim();
      var symbol = document.getElementById('adm-symbol').value.trim();
      var market = document.getElementById('adm-market').value || 'spot';
      if (!name || !symbol){ msg.textContent = '请填写必填项：名称、符号'; return; }
      try{
        var payload = { name: name, symbol: symbol, market_type: market };
        var res = await window.AppApi.request('POST','/scripts', payload, true);
        var data = await window.AppApi.jsonOrThrow(res);
        var extra = [];
        if (data && (data.webhook_url || data.url_token || data.body_secret)){
          if (data.webhook_url) extra.push('Webhook: ' + data.webhook_url);
          if (data.url_token) extra.push('Token: ' + data.url_token);
          if (data.body_secret) extra.push('Secret: ' + data.body_secret);
        }
        msg.textContent = '创建成功' + (extra.length ? '（' + extra.join(' · ') + '）' : '');
        renderResult(data, { name: name, symbol: symbol, market_type: market });
      }catch(err){ msg.textContent = '失败：' + (err && err.message ? err.message : '未知错误'); }
    });

    mount.appendChild(form);
  }

  function renderResult(data, base) {
    var box = document.getElementById('adm-result');
    if (!box) return;
    box.innerHTML = '';
    if (!data) return;
    var fields = [];
    if (data.webhook_url) fields.push({ label: 'Webhook URL', value: data.webhook_url });
    if (data.url_token) fields.push({ label: 'URL Token', value: data.url_token });
    if (data.body_secret) fields.push({ label: 'Body Secret', value: data.body_secret });
    if (!fields.length) return;

    var wrap = el('div', { className: 'card' });
    var title = el('h4', { className: 'card-title', text: '创建结果（可复制/保存）' });
    wrap.appendChild(title);
    for (var i = 0; i < fields.length; i++) {
      (function(row){
        var field = el('div', { className: 'field' });
        var label = el('label', { text: row.label });
        var input = el('input', { className: 'input', value: row.value, readonly: 'readonly' });
        var btn = el('button', { className: 'btn', type: 'button' }); btn.textContent = '复制';
        btn.addEventListener('click', function(){
          if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(row.value).then(function(){}, function(){});
          } else {
            try { input.select(); document.execCommand('copy'); } catch(_) {}
          }
        });
        field.appendChild(label); field.appendChild(input); field.appendChild(btn); wrap.appendChild(field);
      })(fields[i]);
    }

    var saveBtn = el('button', { className: 'btn', type: 'button' }); saveBtn.textContent = '保存到本地';
    saveBtn.addEventListener('click', function(){
      try {
        var content = JSON.stringify({
          name: base && base.name,
          symbol: base && base.symbol,
          market_type: base && base.market_type,
          webhook_url: data.webhook_url,
          url_token: data.url_token,
          body_secret: data.body_secret
        }, null, 2);
        var blob = new Blob([content], { type: 'application/json;charset=utf-8;' });
        var url = URL.createObjectURL(blob);
        var a = document.createElement('a');
        var ts = new Date().toISOString().replace(/[:.]/g,'-');
        a.href = url; a.download = 'strategy_' + (base && base.name ? base.name : 'new') + '_' + ts + '.json';
        a.click(); URL.revokeObjectURL(url);
      } catch (_) {}
    });
    wrap.appendChild(saveBtn);

    var tip = el('p', { className: 'muted small', text: '提示：妥善保管 Token/Secret，避免泄露。' });
    wrap.appendChild(tip);
    box.appendChild(wrap);
  }

  async function init(){
    try{
      var me = await window.AppApi.jsonOrThrow(await window.AppApi.request('GET','/auth/me', null, true));
      var isAdmin = !!(me && (me.role === 'admin' || me.is_admin));
      card.style.display = isAdmin ? '' : 'none';
      if (isAdmin) renderForm();
    }catch(_){ card.style.display = 'none'; }
  }

  init();
})();
